
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var socketio = require('socket.io');
var ioclients = {};
var iosockets = [];

var app = express();

// all environments
app.set('port', process.env.PORT || 3101);
app.set('host', '127.0.0.1');
app.set('views', path.join(__dirname, 'views'));
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
app.use(express.logger());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
  res.send(""); 
});

app.post('/data', function(req, res){
  var session = req.body.session, sender = req.body.sender, update = req.body.update, timestamp = req.body.timestamp, mid = req.body.mid || 1;
  if (session && session.match(/^[0-9a-z]{64}$/) && ioclients[session]) {
    var sl = ioclients[session];
    for (var i = 0; i < sl.length; i++) {
      if (sl[i] && io.sockets.sockets[sl[i]]) {
        io.sockets.sockets[sl[i]].emit('got_update', {"session": session, "update": update });
      }
    }    
  }
  if (sender && sender.match(/^[0-9a-z]{64}$/) && ioclients[sender]) {
    var sn = ioclients[sender];
    for (var i = 0; i < sn.length; i++) {
      if (sn[i] && io.sockets.sockets[sn[i]]) {
        io.sockets.sockets[sn[i]].emit('got_update', {"session": sender, "update": update, "mid": mid });
      }
    }    
  }
  res.send("OK"); 
});

var server = app.listen(app.get('port'), app.get('host'));
var io = socketio.listen(server);

io.sockets.on('connection', function(socket) {
	socket.on('set_session_id', function(sd) {		
		if (sd && sd.session && sd.session.match(/^[0-9a-z]{64}$/)) {
      if (ioclients[sd.session] == undefined) {
        ioclients[sd.session] = [];
      }
      ioclients[sd.session].push(socket.id);
      iosockets[socket.id] = sd.session;
		}
	});	
  socket.on('disconnect', function() {
    var session = iosockets[socket.id];
    var n = ioclients[session].indexOf(socket.id);
    ioclients[session].splice(n, 1);    
  });
});
